﻿using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using eWallet.Security.Cryptography;

namespace eWallet.Data.Local
{
	public partial class eWalletDataSet
	{
		public partial class GroupsRow
		{

			public byte[] EncryptedKey
			{
				get { return this.BlobsRow.Data; }
				set
				{
					if (null != this.BlobsRow)
					{
						this.BlobsRow.Data = value;
					}
					else
					{
						eWalletDataSet ds = (eWalletDataSet)this.Table.DataSet;
						this.BlobsRow = ds.Blobs.AddBlobsRow(Guid.NewGuid(), value);
					}
				}
			}

			public byte[] CreateEncryptedKey(ICryptoModule cryptoModule)
			{
				SymmetricAlgorithm alg = SymmetricAlgorithm.Create("Rijndael");
				return cryptoModule.Encrypt<SymmetricAlgorithm>(alg, CryptoModule.SymmetricAlgorithmInputConverter);
			}

			internal SymmetricAlgorithm DecryptGroupKeyAlgorithm(ICryptoModule cryptoModule)
			{
				if (this.EncryptionMethod != cryptoModule.EncryptionMethod)
					throw new InvalidOperationException(string.Format("The encryption method used to encrypt the current group key was '{0}' but the given crypto module specifies the '{1}' method. Cannot decrypt.", this.EncryptionMethod, cryptoModule.EncryptionMethod));

				if (null == this.BlobsRow)
					throw new InvalidOperationException("The encrypted group key for the current group is not loaded into the Blobs table. Cannot decrypt.");

				return cryptoModule.Decrypt<SymmetricAlgorithm>(this.BlobsRow.Data, CryptoModule.SymmetricAlgorithmOutputConverter);
			}

		}
	}
}
